package com.inspur.icity.bus.api.user.task;

import com.inspur.icity.bus.api.user.model.BusBaseData;
import com.inspur.icity.bus.api.user.model.BusRoute;
import com.inspur.icity.bus.api.user.model.BusSite;
import com.inspur.icity.bus.api.user.service.BusBaseDataService;
import com.inspur.icity.bus.api.user.service.BusRouteService;
import com.inspur.icity.bus.api.user.service.BusSiteService;
import com.inspur.icity.bus.base.core.inspurresult.BusRouter;
import com.inspur.icity.bus.base.core.inspurresult.BusRouterResult;
import com.inspur.icity.bus.base.core.inspurresult.BusStation;
import com.inspur.icity.bus.base.core.inspurresult.BusStationResult;
import com.inspur.icity.bus.base.core.util.InspurApi;
import org.apache.shiro.crypto.hash.Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 定时任务类
 * Created By SOA
 * Date: 2018/1/10
 * Time: 13:51
 */
@Component
public class TaskSaveRouteSite {

    private  static Logger logger = LoggerFactory.getLogger(TaskSaveRouteSite.class);

    @Autowired
    private BusRouteService busRouteService;

    @Autowired
    private BusSiteService busSiteService;

    @Autowired
    private BusBaseDataService baseDataService;

    /**
     * 保存线路站点
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void saveRouteSiteTask1(){
        saveRouteSiteTask();
    }


    /**
     * 保存线路站点
     */
    public void saveRouteSiteTask(){
        long now = System.currentTimeMillis();
        logger.info("定时任务开启--获取线路站点");
        Map<String,Object> map = new HashMap<>();
        map.put("flag",1); // 1：公交查询，2：好运巴士（济南）
        List<BusBaseData> list = baseDataService.find(map);
        saveRouteSite(list); //获取线路、站点
        logger.info("定时任务结束--耗时："+(System.currentTimeMillis() - now));
    }

    /**
     * 业务处理
     */
    @Transactional
    public void saveRouteSite(List<BusBaseData> list){
        /*
        遍历城市
         */
        for(BusBaseData busBaseData : list){
            //获取线路信息
            List<BusRoute> busRoutes = getBusRoute(busBaseData);
            if(null == busRoutes || busRoutes.size() <= 0){
                return;
            }
            //获取所有站点信息
            List<BusSite> busSites = getBusSite(busRoutes,busBaseData);

            //批量删除线路
            busRouteService.batchDelete(busRoutes);
            //批量插入线路
            busRouteService.batchSave(busRoutes);
//            //新增之前先判断（保险）
//            for (BusRoute busRoute : busRoutes){
//                int count = busRouteService.getCount(busRoute);
//                if(count <= 0){
//                    busRouteService.add(busRoute);
//                }
//            }

            //新增之前先去重
            List<BusSite> sites = new ArrayList<>();
            Map<String,Object> map = new HashMap<>();
            for (BusSite busSite:busSites){
                String str = busSite.getAreacode()+busSite.getRouteName()+busSite.getRouteId()+busSite.getUpdown()+busSite.getStationName()+busSite.getStationIndex();
                if(null == map.get(str)){
                    map.put(str,"");
                    sites.add(busSite);
                }
            }
            if(null != sites && sites.size() > 0 ){
                //批量删除站点
                busSiteService.removeByCode(busBaseData.getCode());
                //批量插入站点信息
                busSiteService.batchSave(sites);
            }
        }
    }

    /**
     * 获取线路信息
     * @return
     */
    public List<BusRoute> getBusRoute(BusBaseData busBaseData){
        List<BusRoute> result = new ArrayList<>();
        BusRouterResult busRouterResult = InspurApi.queryAllRoutes(busBaseData.getIcityUri(),busBaseData.getCode(),""); //routeName为空字符时，获取所有线路
        if (busRouterResult != null && busRouterResult.getStatus() != null && "0000".equals(busRouterResult.getStatus())){
            List<BusRouter> busRouters = busRouterResult.getBusRouters();
            Map<String,String> map = new HashMap<>();
            if(null != busRouters){
                for(BusRouter busRouter : busRouters){
                    String str = busRouter.getRouteName()+busRouter.getUpdown()+busRouter.getRouteid(); //过滤重复线路，按照线路id号、线路名称、上下行
                    if(null == map.get(str)){
                        map.put(str,"");
                        BusRoute busRoute = new BusRoute();
                        busRoute.setAreacode(busBaseData.getCode());
                        busRoute.setRouteId(Integer.parseInt(busRouter.getRouteid()));
                        busRoute.setRouteName(busRouter.getRouteName());
                        busRoute.setUpdown(Integer.parseInt(busRouter.getUpdown()));
                        busRoute.setDirection(busRouter.getEndStationName()+"方向"); //方向
                        busRoute.setBeginStationName(busRouter.getBeginStationName());
                        busRoute.setEndStationName(busRouter.getEndStationName());
                        busRoute.setFirstOrder(busRouter.getFirstOrder());
                        busRoute.setLastOrder(busRouter.getLastOrder());
                        busRoute.setStationCount(Integer.parseInt(busRouter.getStationCount()));
                        busRoute.setTicket(busRouter.getTicket()); //票价
                        busRoute.setCreateTime(new Date());
                        result.add(busRoute);
                    }
                }
            }
        }
        return result;
    }

    /**
     * 获取站点信息
     */
    public List<BusSite> getBusSite(List<BusRoute> busRoutes,BusBaseData busBaseData){
        List<BusSite> result = new ArrayList<>();
        Map<String,Object> map = null;
        for(BusRoute busRoute : busRoutes){
            //根据线路获取站点信息
            BusStationResult busStationResult = InspurApi.getStations(busBaseData.getIcityUri(),busRoute.getAreacode(), String.valueOf(busRoute.getRouteId()), String.valueOf(busRoute.getUpdown()));
            if(busStationResult != null && busStationResult.getStatus() != null && "0000".equals(busStationResult.getStatus())){
                List<BusStation> busStations = busStationResult.getBusStations();
                map = new HashMap<>();
                for(BusStation busStation : busStations){
                    String str = busStation.getStationIndex()+busStation.getStationName();
                    if(null == map.get(str)){ //站点排重
                        map.put(str,"");
                        BusSite site = new BusSite();
                        site.setStationName(busStation.getStationName());
                        site.setStationIndex(Integer.parseInt(busStation.getStationIndex()));
                        site.setLng(Double.parseDouble(busStation.getLongitude()));
                        site.setLat(Double.parseDouble(busStation.getLatitude()));
                        site.setRouteName(busRoute.getRouteName());
                        site.setRouteId(busRoute.getRouteId());
                        site.setAreacode(busRoute.getAreacode());
                        site.setDirection(busRoute.getEndStationName()+"方向");
                        site.setUpdown(busRoute.getUpdown());
                        site.setCreatetime(new Date());
                        result.add(site);
                    }
                }
            }
        }
        return result;
    }

}
